//
//  SearchView.swift
//  Juejin App Demo
//
//  Created by 葛鹏 on 2021/8/15.
//

import SwiftUI

struct SearchView: View {
    
    @Binding var searchViewPresented: Bool
    
    @State private var searchText: String = ""
    
    @State private var searchTitleIndex = 0
    
    @EnvironmentObject var searchResultModel: SearchResultModel
    
    var body: some View {
        VStack{
            HStack{
                
                ZStack{
                    
                    Rectangle().foregroundColor(Color(red: 240/255, green: 241/255, blue: 245/255)).cornerRadius(5).frame(height: 40)
                    
                    HStack{
                        
                        Image(systemName: "magnifyingglass").padding(.leading)
                        
                        switch searchTitleIndex{
                        case 0 :
                            TextField(Constants.searchPlaceHolder, text: $searchText)
                        default :
                            TextField("搜索\(Constants.menuTitles[searchTitleIndex])", text: $searchText)
                        }
                        
                        if !searchText.isEmpty {
                            Button(action: {
                                searchText = ""
                            }, label: {
                                Image(systemName: "multiply.circle.fill")
                            }).padding(.trailing, 5).foregroundColor(.gray)
                        }
                        
                        
                    }
                    
                }
                
                Button("取消") {
                    searchViewPresented = false
                }.foregroundColor(.blue)
                
            }.padding()
            
            SearchMenuView(searchTitleIndex: $searchTitleIndex)
            Divider()
            ScrollView{
                SearchSortView(sortViewIsExpanded: false)
                SearchResultDivider()
                ForEach(searchResultModel.results){result in
                    SearchResultCard(searchResult: result)
                    SearchResultDivider()
                }.foregroundColor(.black)
                
            }
            
        }
    }
}

struct SearchView_Previews: PreviewProvider {
    static var previews: some View {
        SearchView(searchViewPresented: .constant(true)).environmentObject(SearchResultModel())
    }
}
